//
//  LStoreProblemListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-8-14.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "LStoreProblemListViewController.h"
#import "StoreItemAddViewController.h"
#import "MTStatusBarOverlay.h"

@interface LStoreProblemListViewController () <UIActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *problemList;
@property (nonatomic, assign) NSInteger selectedRow;


@end

@implementation LStoreProblemListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.problemList = [NSMutableArray array];
    self.selectedRow = -1;
    
    //------------------------------------------------------------------------------------
    //创建长按手势监听
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                               initWithTarget:self
                                               action:@selector(myHandleTableviewCellLongPressed:)];
    
    //代理
    longPress.delegate = self;
    longPress.minimumPressDuration = 1.0;
    //将长按手势添加到需要实现长按操作的视图里
    [self.tableView addGestureRecognizer:longPress];
}

//长按事件的手势监听实现方法
- (void) myHandleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [gestureRecognizer locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
         if(indexPath == nil) return ;
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        NSInteger row = indexPath.row;
        self.selectedRow = row;
        
        NSString *titleName = @"";
        if (self.viewType == EnterFromDRDD) {
            titleName = @"忽略";
        } else if (self.viewType == EnterFromCCSQ) {
            titleName = @"删除";
        }
        if ([titleName length] > 0) {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@""
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                 destructiveButtonTitle:titleName
                                                      otherButtonTitles: nil];
            [sheet showInView:self.view];
        }
    }
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        NSLog(@"UIGestureRecognizerStateChanged");
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    if (self.viewType == EnterFromDRDD) {
        self.title = @"临店项目";
        self.showLeftBtn = YES;
        self.showRightBtn = NO;
    } else if (self.viewType == EnterFromCCSQ) {
        self.title = @"临店项目列表";
        self.showLeftBtn = YES;
        self.showRightBtn = YES;
    } else if (self.viewType == EnterFromCCBG) {
        self.title = @"临店项目";
        self.showLeftBtn = YES;
        self.showRightBtn = YES;
    }
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    if (self.viewType == EnterFromCCSQ || self.viewType == EnterFromCCBG) {
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_新增_n.png"] forState:UIControlStateNormal];
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_新增_p.png"] forState:UIControlStateHighlighted];
    }
    
    [self performSelector:@selector(getStoreProblemListOfCurrentPici) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getStoreProblemListOfCurrentPici];
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightNavItemAction:(id)sender {
    [self addStoreItem];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//获取当前申请批次的临店项目列表
- (void)getStoreProblemListOfCurrentPici {
    if ([self.erandInfo count] > 0 && !self.isRefreshing) {
        NSString *pc = [self.erandInfo objectForKeyOrNil:@"pc"];
        if ([pc length] > 0) {
            [self getStoreProblemListWithPici:pc];
        } else {
            NSLog(@"*******出差变更审批，pc为空值");
        }
        self.isRefreshing = YES;
    }
}

- (void)getStoreProblemListWithPici:(NSString *)pc {
    if ([pc length] == 0) {
        return;
    }
//    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:pc,@"pc",nil];
//    [self.networkManager requestWithMethod:showProjectByPc parameter:param delegate:self];
//    [self.HUD show:YES];
    
//    UserInfo *user = [UserInfo instance];
//    NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"];
    NSString *gonghao = [self.erandInfo objectForKeyOrNil:@"gh"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           gonghao,@"gh",
                           pc,@"pc",
                           nil];
    if([self sfbg]){
        [self.networkManager requestWithMethod:projects2 parameter:param delegate:self];
    } else {
        [self.networkManager requestWithMethod:projects parameter:param delegate:self];
    }
    [self.HUD show:YES];
}

//新增临店项目
- (void)addStoreItem {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    StoreItemAddViewController *addVC = (StoreItemAddViewController *)[storyboard instantiateViewControllerWithIdentifier:@"StoreItemAddView"];
    addVC.erandInfo = self.erandInfo;
    [self.navigationController pushViewController:addVC animated:YES];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if (methodId == projects || methodId == projects2) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                self.problemList = [NSMutableArray array];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *problems = [dataObject objectForKeyOrNil:@"projects"];
                        if (![problems isKindOfClass:[NSNull class]] && [problems count] > 0) {
                            [self.problemList  addObjectsFromArray:problems];
                        }
                    }
                }
                
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"临店项目获取失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        [self.tableView reloadData];
    } else if (methodId == ignoreWorkApply || methodId == deleteProjectById) { //忽略临店项目
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSInteger resultCode = [[dataObject objectForKeyOrNil:@"reslut"] integerValue];
                        if (resultCode == 0) {
                            
                            NSString *msg = @"";
                            if (methodId == ignoreWorkApply) {
                                msg = @"忽略临店项目成功";
                            } else if (methodId == deleteProjectById) {
                                msg = @"删除临店项目成功";
                            }
                            
                            [self showAlertViewWithMessage:msg];
                            
//                            MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                            overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                            overlay.detailViewMode = MTDetailViewModeDetailText;
//                            overlay.delegate = nil;
//                            overlay.progress = 0.0;
//                            if (methodId == ignoreWorkApply) {
//                                [overlay postFinishMessage:@"忽略临店项目成功！" duration:1.6 animated:YES];
//                            } else if (methodId == deleteProjectById) {
//                                [overlay postFinishMessage:@"删除临店项目成功！" duration:1.6 animated:YES];
//                            }
//                            overlay.progress = 1.8;
                            
                        }
                    }
                }
                
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    if (methodId == ignoreWorkApply) {
                        msg = @"忽略临店项目失败，请稍后重试";
                    } else if (methodId == deleteProjectById) {
                        msg = @"删除临店项目失败，请稍后重试";
                    }
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        
        [self performSelector:@selector(getStoreProblemListOfCurrentPici) withObject:nil afterDelay:1.8];
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == selectUserinfoByLeaderGh) {
                msg = @"临店项目获取失败，请稍后重试";
            } else if (methodId == ignoreWorkApply) {
                msg = @"临店项目忽略失败，请稍后重试";
            } else if (methodId == deleteProjectById) {
                msg = @"删除临店项目失败，请稍后重试";
            }
            
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 5;
    return [self.problemList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"LStoreProblemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *label3 = (UILabel *)[cell.contentView viewWithTag:103];
    UIButton *statusBtn = (UIButton *)[cell.contentView viewWithTag:104];
    
    NSInteger row = indexPath.row;
    
    if ([self.problemList count] > row) {
        NSDictionary *cellData = [self.problemList objectAtIndex:row];
//        NSInteger ldpc = [[cellData objectForKeyOrNil:@"ldpc"] integerValue]; //临店批次
        NSString *name = [cellData objectForKeyOrNil:@"xmmc"]; //项目名称 --> 项目简介
        BOOL needPhoto = [[cellData objectForKeyOrNil:@"sfpz"] boolValue]; //是否需要拍照
        BOOL mustFinish = [[cellData objectForKeyOrNil:@"sfbx"] boolValue]; //是否必须完成
        
        NSString *strTitle = @"";
        if (mustFinish) {
            strTitle = @"必须完成";
        }
        label1.text = strTitle;
        label3.text = name;
        
        NSString *description = @"";

        if (needPhoto) {
            description = @"需拍照";
        }
        label2.text = description;
        
        if (self.viewType == EnterFromDRDD) {
            statusBtn.hidden = NO;
            
            BOOL finished = [[cellData objectForKeyOrNil:@"sftj"] boolValue]; //是否提交
            if (finished) {
                [statusBtn setTitle:@"已提交" forState:UIControlStateNormal];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_通过.png"] forState:UIControlStateNormal];
            } else {
                [statusBtn setTitle:@"未提交" forState:UIControlStateNormal];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_未通过.png"] forState:UIControlStateNormal];
            }
        } else {
            statusBtn.hidden = YES;
        }
        
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *cellData = [self.problemList objectAtIndex:indexPath.row];
    NSString *name = [cellData objectForKeyOrNil:@"xmms"];
    
    
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"项目详情" message:name delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    
    
    [alter show];
    
    }



#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == actionSheet.destructiveButtonIndex) {
        if ([self.problemList count] > self.selectedRow && self.selectedRow >= 0) {
            NSDictionary *storeInfo = [self.problemList objectAtIndex:self.selectedRow];
            NSString *itemID = [storeInfo objectForKey:@"id"];
            
            if (self.viewType == EnterFromDRDD) {
                NSString *pc = @""; //临店批次
                pc = [self.erandInfo objectForKeyOrNil:@"pc"];
                
//                UserInfo *user = [UserInfo instance];
//                NSString *gonghao = [user.info objectForKeyOrNil:@"yhm"]; //领导工号
                NSString *gonghao = [self.erandInfo objectForKeyOrNil:@"gh"];
                NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                       itemID,@"id",
                                       pc,@"pc",
                                       gonghao,@"gh", nil];
                [self.networkManager requestWithMethod:ignoreWorkApply parameter:param delegate:self];
                [self.HUD show:YES];
            } else if (self.viewType == EnterFromCCSQ) {
                NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                       itemID,@"id", nil];
                [self.networkManager requestWithMethod:deleteProjectById parameter:param delegate:self];
                [self.HUD show:YES];
            }
            
        }
    }
}

@end
